<?php

class ClassToken extends \FiradioPHP\Routing\Router {

    private $aConfig;

    public function __construct($conf = array()) {
        $this->aConfig = $conf['config'];
    }

    public function TokenEncode($token_info, $token_key_new = NULL) {
        $token_key = $this->aConfig['token_key'];
        if (!empty($token_key_new)) {
            $token_key = $token_key_new;
        }
        if (is_array($token_info)) {
            $token_info = json_encode($token_info);
        }
        $token_xxtea_base64 = base64_encode(xxtea_encrypt($token_info, $token_key));
        return $token_xxtea_base64;
    }

    public function TokenDecode($token_xxtea_base64, $token_key_new = NULL) {
        $token_key = $this->aConfig['token_key'];
        if (!empty($token_key_new)) {
            $token_key = $token_key_new;
        }
        if (empty($token_xxtea_base64)) {
            $this->error('请先登录', 401);
        }
        $token_json = xxtea_decrypt(base64_decode($token_xxtea_base64), $token_key);
        if (empty($token_json)) {
            $this->error('请重新登录', 401);
        }
        if (substr($token_json, 0, 1) == '{') {
            $token_info = json_decode($token_json, TRUE);
            if (empty($token_info)) {
                $this->error('您提供的token解析JSON失败', 401);
            }
        } else {
            $aToken = explode('|', $token_json);
            if (count($aToken) < 2) {
                $this->error('您提供的token分割信息失败', 401);
            }
            $token_info = array();
            $token_info['login_time'] = isset($aToken[0]) ? doubleval($aToken[0]) / 1000 : 0;
            $token_info['user_id'] = isset($aToken[1]) ? intval($aToken[1]) : 0;
            $token_info['login_ip'] = isset($aToken[2]) ? $aToken[2] : '';
            $token_info['plat'] = isset($aToken[3]) ? $aToken[3] : '';
            return $token_info;
        }
        return $token_info;
    }

}
